// Copyright (c) 2022, hzmes and contributors
// For license information, please see license.txt

frappe.ui.form.on('SRM AP Reconciliation', {
	onload: function(frm) {
		let is_allowed = frappe.user_roles.includes('SRM Supplier');
		frm.set_df_property('supplier_number', 'read_only', is_allowed);
		if (frm.is_new()) {
			frm.set_intro('请设置起始日期范围并保存', 'green');
		}
	},

	refresh: function(frm) {

		frm.add_custom_button(__('Go To Page'),function() {
			frappe.route_options = {reconciliation_billno: frm.doc.name};
			frappe.set_route("/app/Reconciliation/");
		});

		if (!frm.is_new() && frm.doc.date_from && frm.doc.date_to) {
			frm.add_custom_button(__('Create'),function() {	
				// 判断是否有历史未对账的出货明细
				frappe.db.count('SRM Purchase Delivery Sub', { is_reconciliation: 0 })
				.then( (count) => {
					if (count>0) {frm.add_custom_button(__('History'),function() {
						frappe.msgprint(`有 ${count} 条超期未对账出货明细`);
						// call py method...
					})}
				});
				if (frm.doc.date_from && frm.doc.date_to) {
					frappe.call({
						method: "get_ap_reconciliation",
						doc: frm.doc,
						freeze: true,
						freeze_message: __("running..."),
						callback: function(r) {
							console.log(r);
							frm.refresh();
						}
					});
				}
				else {frappe.msgprint('hehe')}
			})
		}
	}
});
